/**
 *
 */
package spring.tutorial.web;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.request.WebRequest;

import spring.tutorial.dao.MoimDao;
import spring.tutorial.domain.Moim;

/**
 * @author chan_wook
 *
 * tutorial for Multi-action controller
 *
 */
@Controller
@SessionAttributes("moim")
public class MoimController {

	@Autowired
	private MoimDao moimDao;

	@RequestMapping("/list.html")
	public ModelMap list(ModelMap model) {
		model.addAttribute("moimList", moimDao.getAll());
		return model;
	}

	@RequestMapping("/view.html")
	public ModelMap view(@RequestParam("moimId")
	long moimId, ModelMap model) {
		model.addAttribute("moim", moimDao.get(moimId));
		return model;
	}

	@RequestMapping("/delete.html")
	public String delete(@RequestParam("moimId")
	long moimId) {
		moimDao.delete(moimId);
		return "redirect:list.html";
	}

	@RequestMapping(value = { "/create.html", "/update.html" }, method = RequestMethod.GET)
	public String setupForm(ModelMap model, WebRequest request) {
		String moimId = request.getParameter("moimId");

		if (moimId == null) {
			model.addAttribute("moim", new Moim());
		} else {
			model.addAttribute("moim", moimDao.get(Long.parseLong(moimId)));
		}
		return "form";
	}

	@RequestMapping(value = "/form.html", method = RequestMethod.POST)
	public String submit(@ModelAttribute("moim")
	Moim moim, BindingResult bindingResult) {
		new MoimValidator();
		if (bindingResult.hasErrors()) {
			return "form";
		} else {
			moimDao.saveOrUpdate(moim);
			return "redirect:list.html";
		}
	}

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				dateFormat, false));
	}
}
